<?php
include 'portlet_header.php';
if (getParameter("operation")!=null) $operation=getParameter("operation");
if (getParameter("portlet")!=null) $portlet=getParameter("portlet");
if (getParameter("portletId")!=null) $portletId=getParameter("portletId");
if (getParameter("pageId")!=null) $pageId=getParameter("pageId");

if (getParameter("portalId")!=null) $portalId=getParameter("portalId");
if ($operation=="getproducts")
{
	
	if(isset($_GET['term'])) {
		$q = htmlentities($_GET['term']); // protection
		 
		$results = array();
		
	
		
		
		$sSql = "SELECT lib_FR as lib, id FROM evigie_products WHERE UPPER(lib_FR) LIKE UPPER('%". $q ."%') LIMIT 0, 10";
		
	//	echo $sSql;
	

		
		$rs=$GLOBALS["conn"]->Execute($sSql);

			
		while ($rs && !$rs->EOF)  {
		
	
		
			//echo '"'.$rs->fields["id"].'": "'.$rs->fields["lib"].'"'.'\n';
			
			$results[] = array(
					'label'    => $rs->fields["lib"],
					'value' => $rs->fields["id"]
					
			);
		    $rs->MoveNext();
		
		
		}
		
	
			
		// modify your http header to json, to help browsers to naturally handle your response with
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');
		
		echo json_encode($results);
		
	}
	
	
}elseif ($operation=="findproductsxx")
{
	
	
	$startwith=array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
	set_time_limit(0);
	//count($startwith)
	$GLOBALS["conn"]->Execute("TRUNCATE TABLE evigie_products;");
	$maxrows=10000;
	for ($i=0;$i<count($startwith);$i++){
	
		$url="http://ma.kompass.com/MarketingViewWeb/rest2/autocomplet?featureClass=P&style=full&maxRows=$maxrows&searchGeoCode=MKT_WW&searchMode=0&name_startsWith=$startwith[$i]";
	
	//echo $url."<br/>";
	

	
		
	$output = file_get_contents($url);
	// echo $output;
	$results=preg_split("/\"},{\"/",$output);
	$GLOBALS["conn"]->BeginTrans();
	for($j=0;$j<count($results);$j++ )
	{
	//	print_r($results);
		
		$tmp=preg_split("/\",\"value\":\"/",$results[$j]);
		$tmplabel=preg_split("/label\":\"/",$tmp[0]);
		if (count($tmplabel)>1){
		$tmplabel=$tmplabel[1];
		echo "Label : ".$tmplabel."<br/>";
		
		$tmp=preg_split("/\"}],\"/",$tmp[1]);
		$tmp=$tmp[0];
		echo "Value : ".$tmp."<br/>";
	
		$sql="INSERT IGNORE INTO evigie_products VALUES (NULL,'$tmp','$tmplabel');";
		$GLOBALS["conn"]->Execute($sql);
		}
	}
	$GLOBALS["conn"]->CommitTrans();
	}
	
	

	
	
}elseif ($operation=="searchkompass")
{
global $LANG,$lang;
$productId=getParameter("productId");
    if ($productId!=null){
    //loign fisrt

    
    	
    	
    $params=array("_nfpb",
        "_windowLabel",
        "searchPdtSvces_1_1_actionOverride",
        "searchPdtSvces_1_1searchExp",
        "searchPdtSvces_1_1geoSearch",
        "searchPdtSvces_1_1geoUnitGeoScopeRegion",
        "searchPdtSvces_1_1geoDistributionCode",
        "searchPdtSvces_1_1geoUnitGeoScopeCountry",
        "searchPdtSvces_1_1geoUnitGeoScopeDistrict",
        "searchPdtSvces_1_1CodeLevel",
        "searchPdtSvces_1_1_forceGUILanguage",
        "searchPdtSvces_1_1geoCode",
        "searchPdtSvces_1_1typeOfGeoDistribution",
        "searchPdtSvces_1_1CodeId",
        "_pageLabel"
    );
    
/*
    $params=array("mktInfo_BasicSearchPortlet_1isMainSearch",
    		"_nfpb",
    		"_windowLabel",
    		"mktInfo_BasicSearchPortlet_1_actionOverride",
    		"_pageLabel",
    		"mktInfo_BasicSearchPortlet_1{actionForm.userLanguage}",
    		"mktInfo_BasicSearchPortlet_1{actionForm.userParameterSearch}",
    		"mktInfo_BasicSearchPortlet_1wlw-select_key:{actionForm.geoSearch}OldValue",
    		"mktInfo_BasicSearchPortlet_1wlw-select_key:{actionForm.geoSearch}",
    		"mktInfo_BasicSearchPortlet_1wlw-select_key:{actionForm.typeSearch}OldValue",
    		"mktInfo_BasicSearchPortlet_1wlw-select_key:{actionForm.typeSearch}"
    );*/
    
        $productLib=getObjByKey("evigie_products","lib_$LANG","id",$productId);
        $aoId=getParameter("aoId");
        $productCode=getParameter("productCode");

        //mktInfo_BasicSearchPortlet_1wlw-select_key:{actionForm.geoSearch}:MAR
        
        $country=getParameter("countryCode");
        $countryprefix="country.";
        $typeOfGeoDistribution="MKT_COUNTRY";
        if ($country==null) {
        	$country="MKT_WW";
        	$countryprefix="";
        	$typeOfGeoDistribution="MKT_WW";
        }
  $values=array("true",
        "searchPdtSvces_1_1",
        "/flows/marketingInformation/searchPdtSvces/displayList",
        $productLib,
        $country,
        "",
        $country,
        $country,
        "",
        strlen($productCode),
        "fr",
        $countryprefix.$country, //MKT_WW
        $typeOfGeoDistribution, //MKT_WW
        $productCode,
        "marketingInformation_productServicesPage");/*
        
        $values=array("true",
        		"true",
        		"mktInfo_BasicSearchPortlet_1",
        		"%2Fflows%2FmarketingInformation%2FbasicSearch%2FlaunchSearch",
        		"common_homePage",
        		"fr",
        		$productLib,
        		true,
        		$country,
        		true,
        		"PS");*/
    $url="http://ma.kompass.com/MarketingViewWeb/appmanager/kim/MAR_Portal";

    /*
     *
     *
     * http://ma.kompass.com/MarketingViewWeb/appmanager/kim/MAR_Portal
http://ma.kompass.com/MarketingViewWeb/appmanager/kim/MAR_Portal
_nfpb=true
_windowLabel=searchPdtSvces_1_1
searchPdtSvces_1_1_actionOverride=/flows/marketingInformation/searchPdtSvces/displayList
searchPdtSvces_1_1searchExp=Protection Inondations
searchPdtSvces_1_1geoSearch=MKT_WW
searchPdtSvces_1_1geoUnitGeoScopeRegion=
searchPdtSvces_1_1geoDistributionCode=MKT_WW
searchPdtSvces_1_1geoUnitGeoScopeCountry=
searchPdtSvces_1_1geoUnitGeoScopeDistrict=
searchPdtSvces_1_1CodeLevel=7
searchPdtSvces_1_1_forceGUILanguage=fr
searchPdtSvces_1_1geoCode=MKT_WW
searchPdtSvces_1_1typeOfGeoDistribution=MKT_WW
searchPdtSvces_1_1CodeId=5405030
_pageLabel=marketingInformation_productServicesPage
     */

    for($i=0;$i<count($params);$i++ )
    {
        $url=addParameter($params[$i],$values[$i],$url);

    }

  $GLOBALS["conn"]->BeginTrans();
set_time_limit(0);

        echo $url."<br/>";
    $output = file_get_contents($url);
   // echo $output;
 $results=preg_split("/item_resultat_mea/",$output);

    //anchor_submit_form('result_research','
    //');return false;"
   echo count($results);
    //count($results)
   $previous_website=null;
   $previous_logo=null;
    for($i=1;$i<count($results);$i++ )
    {
        $link=preg_split("/anchor_submit_form/",$results[$i]);
        $link=preg_split("/return false/",$link[1]);
        $link=str_ireplace("('result_research','","",$link[0]);
        $link=str_ireplace("');","",$link);

  echo $link."<br/>";

        $html = file_get_contents($link);
        echo "Enterprise <br/><br/>";


        $doc = new DOMDocument();
        libxml_use_internal_errors(true);
        
        //echo $html;
        $doc->loadHTML($html); // loads your HTML
        $xpath = new DOMXPath($doc);
// returns a list of all links with rel=nofollow

        $vars=array("companyName","website","streetAddress","postalCode","addressLocality","addressCountry","telephone","faxNumber","logo");
        $filters=array("div[@itemprop='name']","a[@class='p_SiteInternet']","span[@itemprop='streetAddress']","span[@itemprop='postalCode']","span[@itemprop='addressLocality']","span[@itemprop='addressCountry']","span[@itemprop='telephone']","span[@itemprop='faxNumber']","img[@itemprop='logo']");

//count($vars)
        $website="";
        $logo="";
        for($j=0;$j<count($vars);$j++ )
        {
            $nodelist = $xpath->query("//".$filters[$j]);
            $var=$vars[$j];
          /*  foreach($nodelist as $node) {
                # Show the <a href>
                $test=$node->nodeValue;
                echo $test."<br/>";

            }*/
            if ($nodelist->length>0){
         //   echo $nodelist->item(0)->nodeValue;

         	//if ( $$var==$previous_$var)  $$var=""; else
            $$var=$nodelist->item(0)->nodeValue;

                if ($var=="logo") {
                	//TODO if current logo match the previous one , should insert a no image logo 
                    $logourl="http://fr.kompass.com".$nodelist->item(0)->attributes->getNamedItem("src")->nodeValue;

                    $logo=preg_split("#\/#",$logourl);
                    $logo=$logo[count($logo)-1];
                    //$img = '/my/folder/flower.gif';
                    $logo="logo_".rand_string(10)."_".$logo;
                    file_put_contents(getFilesPath("logos")."/".$logo, file_get_contents($logourl));
                }elseif ($var=="website") {

                	$website=$nodelist->item(0)->attributes->getNamedItem("href")->nodeValue;
                	

                }
            } 
        }
        
        if ($website==$previous_website) $website=""; else
        	$previous_website=$website;
        
        if ($logo==$previous_logo) $logo=""; else
        	$previous_logo=$logo;
        
        
        //get the id of the country , and if does not exist store it and get his id
        
        $countryId=getObjByKey("portal_countries","id","lib_FR",$addressCountry);
        
        if ($countryId==null) {
        	insertObjByKey("portal_countries","id","lib_FR",NULL,$addressCountry);
        	
        	$countryId=getLastId();
        }
        
        
        $cityId=getObjByKey("portal_cities","id","lib_lt",$addressLocality);
        
        if ($cityId==null) {
        	insertObjByKey("portal_cities","id","lib_lt","countryId",NULL,$addressLocality,$countryId);
        	 
        	$cityId=getLastId();
        }
        

       $sql="INSERT IGNORE INTO evigie_providers VALUES (NULL,$portalId,'$companyName','$website','$streetAddress','$postalCode',$cityId,$countryId,'$telephone','$faxNumber','$logo','')";

        echo $sql."<br/>";

     $GLOBALS["conn"]->Execute($sql);
        $providerId=getLastId();
       if ($providerId==0 || $providerId==null) goto error; 


        //if nothing inserted delete the image

        $sql="INSERT IGNORE INTO evigie_provider_products VALUES (NULL,$providerId,$productId)";
   echo $sql."<br/>";
    $GLOBALS["conn"]->Execute($sql);
        //echo $sql;
     /*   foreach($nodelist as $node) {
            # Show the <a href>
            $companyname=$node->nodeValue;
            echo $companyname."<br/>";

        }/*

        /*
         * img itemprop="logo"
         * a class="p_SiteInternet"
         * div name
         * span
         * itemprop="streetAddress"

        postalCode
addressLocality
        addressCountry
        telephone
        faxNumber
        */


        echo " <br/><br/>########## <br/><br/>";
    }
    $GLOBALS["conn"]->CommitTrans();
	header("Location: ".addParameter("succes","Recherche Accomplie",$_SERVER['HTTP_REFERER']));
    }else{

    	error:
        header("Location: ".addParameter("error","Probleme survenu",$_SERVER['HTTP_REFERER']));
    }


//echo $output;
    //header("Location: ".addParameter("succes","Recherche Accomplie",$_SERVER['HTTP_REFERER']));
}
include 'portlet_footer.php';
?>